#include <WiFi.h>

const char* ssid = "QQ";
const char* password = "123456qq";

WiFiServer server(81); // 设置服务器端口为81

void setup() {
  Serial.begin(115200);
  //D2引脚
  pinMode(LED_BUILTIN, OUTPUT);

  // 连接WiFi网络
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // 打印ESP32的IP地址
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());

  // 启动服务器
  server.begin();
  Serial.println("Server started");
}

void loop() {
  // 等待客户端连接
  WiFiClient client = server.available();
  if (client) {
    
    // 读取客户端请求
    String request = client.readStringUntil('\r');
    Serial.println("Request: " + request);
    //在处理完请求后通常会调用client.flush()方法来清空输入缓冲区 以确保下一个请求能够被正确处理。
    client.flush();

    // 检查请求路径中是否包含"/on"的子字符串 没有则返回-1
    if (request.indexOf("/on") != -1) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED ON");
    } else if (request.indexOf("/off") != -1) {
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED OFF");
    }

    // 返回响应
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");
    client.println("<head><title>ESP32 LED Control</title></head>");
    client.println("<body>");
    client.println("<h1>ESP32 LED Control</h1>");
    client.println("<p>Click <a href=\"/on\">here</a> to turn the LED on</p>");
    client.println("<p>Click <a href=\"/off\">here</a> to turn the LED off</p>");
    client.println("</body>");
    client.println("</html>");

    // 断开客户端连接
    client.stop();
  }
}

